<template>
  <div class="account-security">
    <el-card class="security-card">
      <h3 class="title">账号安全</h3>

      <el-form :model="pwdForm" :rules="rules" ref="pwdRef" label-width="120px">

        <el-form-item label="原密码" prop="oldPassword">
          <el-input v-model="pwdForm.oldPassword" type="password" />
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="pwdForm.newPassword" type="password" />
        </el-form-item>

        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input v-model="pwdForm.confirmPassword" type="password" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submit">修改密码</el-button>
        </el-form-item>

      </el-form>
    </el-card>
  </div>
</template>

<script>
import request from '@/utils/request'
import { ElMessage } from 'element-plus'



export default {
  data() {
    return {
      // 表单数据
      pwdForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: '',
      },
      rules: {
        oldPassword: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
        newPassword: [{ required: true, message: '请输入新密码', trigger: 'blur' }],
        confirmPassword: [
          { required: true, message: '请确认新密码', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value !== this.pwdForm.newPassword) {
                callback(new Error('两次输入的密码不一致'));
              } else callback();
            },
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    async submit() {
      this.$refs.pwdRef.validate(async valid => {
        if (!valid) return;
        // 调用后端修改密码接口
        try {
            const res = await request.put('/user/updatePassword', {
                // id: localStorage.getItem("adminId"),
                oldPassword: this.pwdForm.oldPassword,
                newPassword: this.pwdForm.newPassword,
                confirmPassword: this.pwdForm.confirmPassword,
            })
            console.log(res)
            if (res.data.code === 200) {
                ElMessage.success('更新成功')
                this.$router.push({ name: 'Login' })
                localStorage.clear()
            } else {
                ElMessage.error(res.data.message || '更新失败')
            }
        } catch (error) {
          ElMessage.error(error.message || '更新失败')
          this.$router.push({ name: 'Login' })
          localStorage.clear()
        }
      });
    }
  }
}
</script>

<style scoped>
.account-security {
  width: 500px;
  margin: 0 auto;
}

.security-card {
  padding: 20px 30px;
}
</style>
